package com.hangsu.train.core.result;

import org.apache.commons.lang3.StringUtils;

/**
 * @author lyy
 */
public class Resp<T> {

    private T data;
    private int code;
    private String message;

    private static <T> Resp<T> newInstance(Err err, String message, T data) {
        Resp<T> resp = new Resp<>();
        resp.setData(data);
        resp.setCode(err.getCode());
        resp.setMessage(StringUtils.isNotEmpty(message) ? message : err.getMessage());
        return resp;
    }

    public static <T> Resp<T> ok() {
        return newInstance(Err.OK, null, null);
    }

    public static <T> Resp<T> ok(T t) {
        return newInstance(Err.OK, null, t);
    }

    public static <T> Resp<T> fail() {
        return newInstance(Err.ERR, null, null);
    }

    public static <T> Resp<T> fail(Err err) {
        return newInstance(err, null, null);
    }

    public static <T> Resp<T> fail(Err err, String message) {
        return newInstance(err, message, null);
    }

    public static <T> Resp<T> ret(boolean flag) {
        return flag ? ok() : fail(Err.ERR);
    }

    public boolean isSuccess() {
        return this.getCode() == Err.OK.getCode();
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
